﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Utility.Inspector.ReorderableList;
using Utility.Inspector;
using Utility.Math;
using TerrainSystem;
using Utility.DataSystem;

namespace DataSystem
{
	public class TileGroupSettingEditorWindow : SettingObjectEditorWindow<TileGroupSettingObject>
	{
		protected override GUIContent TitleContent => new GUIContent ("地块组设定");
		protected override string SettingPath => EditorConstants.RootPath_TileGroupSettings;
		protected override bool CanDisable => true;

		[MenuItem ("Settings/地块组设定")]
		protected static void OpenWindow ()
		{
			OpenWindow<TileGroupSettingEditorWindow> ();
		}

		[UnityEditor.Callbacks.OnOpenAsset (0)]
		protected static bool OnOpenAsset (int instId, int line)
		{
			return OnOpenAsset<TileGroupSettingEditorWindow> (instId, line);
		}

		Color color_void = new Color (0.2f, 0.2f, 0.2f);
		Color[] colors = new Color[8]
		{
			Color.white,
			Color.green,
			Color.blue,
			Color.red,
			Color.cyan,
			Color.yellow,
			Color.magenta,
			Color.gray,
		};

		Color GetColor (int id)
		{
			if (id < 0)
			{
				return color_void;
			}
			if (id >= 8)
			{
				return colors[7];
			}
			return colors[id];
		}

		int selectedIndex = 0;
		bool showTileId = false;
		bool showBuildingOrien = false;

		int editType = 0;
		string[] editTypes = new string[] { "无", "地块", "建筑" };

		Vector2 scrollPos_grid;

		protected override void DrawSetting ()
		{
			Setting.bilateralSymmetry_half = EditorGUILayoutEX.ObjectField ("左右对称的另一半", Setting.bilateralSymmetry_half, false);
			Setting.category = EditorGUILayoutEX.EnumPopup ("类别", Setting.category);
			Setting.overlapType = EditorGUILayoutEX.EnumPopup ("覆盖类型", Setting.overlapType);
			Setting.beOverlappedType = EditorGUILayoutEX.EnumPopup ("被覆盖类型", Setting.beOverlappedType);
			switch (Setting.category)
			{
				case TileGroupSetting.Categorys.Platform:
					//Setting.canGainAsSupply = EditorGUILayout.Toggle ("可以作为补给获取", Setting.canGainAsSupply);
					//Setting.requiredMinDifficulty = EditorGUILayout.IntField ("最低所需难度", Setting.requiredMinDifficulty);
					break;
			}

			Setting.canCompleteOverlap = EditorGUILayout.Toggle ("可以完全重叠", Setting.canCompleteOverlap);

			EditorGUILayout.LabelField ("地块类型");
			ListDrawer.DrawObjectList (Setting.tileSettings, false, ReorderableListFlags.ShowIndices);

			Setting.SetGridSize (EditorGUILayout.Vector2IntField ("网格大小", Setting.gridSize));
			Setting.SetGridCenter (EditorGUILayout.Vector2IntField ("网格中心", Setting.gridCenter));

			EditorGUILayout.LabelField ("网格");
			//buttons
			using (HorizontalScope.New (FlexibleTypes.End))
			{
				showTileId = GUILayout.Toggle (showTileId, "显示地块Id", "button");
				showBuildingOrien = GUILayout.Toggle (showBuildingOrien, "显示建筑朝向", "button");
			}
			//edit
			using (HorizontalScope.New (FlexibleTypes.Begin))
			{
				editType = GUILayout.Toolbar (editType, editTypes);
			}

			//grid
			DrawGrid ();

			//cell setting
			DrawCellSetting ();
		}

		void DrawGrid ()
		{
			Vector2 cellSize = new Vector2 (40, 40);
			float w = Setting.gridSize.x * cellSize.x + 20;
			float h = Setting.gridSize.y * cellSize.y;

			var style_centeredLabel = new GUIStyle (EditorStyles.label)
			{
				alignment = TextAnchor.MiddleCenter
			};

			using (ScrollViewScope.New (ref scrollPos_grid, GUILayout.Height (h + 20)))
			{
				Rect rect = GUILayoutUtility.GetRect (w, h);
				Vector2 origin = new Vector2 (rect.xMin + 20, rect.yMax);

				for (int i = 0; i < Setting.cellDataMap.Length; i++)
				{
					Vector2Int gridCoord = Setting.IndexToCoord (i);

					Vector2 cellOrigin = origin + new Vector2 (gridCoord.x * cellSize.x, -(gridCoord.y + 1) * cellSize.y);
					Rect rect_cell = new Rect (cellOrigin, cellSize);

					bool isCenter = Setting.gridCenter == gridCoord;
					int index = Setting.CoordToIndex (gridCoord);
					var cellData = Setting.cellDataMap[index];
					bool selected = index == selectedIndex;

					var newCellData = cellData;

					var tileSetting = GetTileSetting (cellData.tileIndex);

					bool hasTile = tileSetting != null;

					bool canBuild = hasTile && tileSetting.canBuild;

					//cell-bg
					//Color c_tile = GetColor (cellData.tileIndex);
					Color c_tile = tileSetting?.color ?? Color.clear;
					if (selected)
					{
						using (GUIColorScope.New (Color.yellow))
						{
							GUI.Box (rect_cell, "");
						}
						{
							//GUI.Box (rect_cell.Shrink (6, 6), "");
							using (GUIColorScope.New (c_tile))
							{
								if (tileSetting?.texture)
									GUI.Box (rect_cell.Shrink (4, 4), new GUIContent(tileSetting.texture));
								else
									GUI.Box (rect_cell.Shrink (4, 4), "");
							}
						}
					}
					else
					{
						using (GUIColorScope.New (c_tile))
						{
							if (tileSetting?.texture)
								GUI.Box (rect_cell, new GUIContent(tileSetting.texture));
							else
								GUI.Box (rect_cell, "");
						}
					}

					//edit
					switch (editType)
					{
						case 1://地块
							newCellData.tileIndex = EditorGUI.IntField (rect_cell.Shrink (20, 20), cellData.tileIndex);
							break;
						case 2://建筑
							newCellData.buildingIndex = EditorGUI.IntField (rect_cell.Shrink (20, 20), cellData.buildingIndex);
							break;
					}

					//select
					if (GUI.Button (rect_cell, GUIContent.none, GUIStyle.none))
					{
						selectedIndex = selected ? -1 : index;
					}

					//center
					if (isCenter)
					{
						Rect rect_centerIcon = rect_cell.Divide (3, 3).ShiftRight ().ShiftRight ();
						using (GUIColorScope.New (Color.yellow))
						{
							GUI.Box (rect_centerIcon, "");
						}
						GUI.Label (rect_centerIcon, "C", style_centeredLabel);
					}

					//tile id
					if (showTileId)
					{
						Rect rect_tileId = rect_cell.Divide (3, 3);
						GUI.Box (rect_tileId, "");
						GUI.Label (rect_tileId, cellData.tileIndex.ToString (), style_centeredLabel);
					}

					Setting.cellDataMap[index] = newCellData;
				}

			}
		}

		void DrawCellSetting ()
		{
			int index = selectedIndex;
			if (index < 0 || index >= Setting.cellDataMap.Length)
			{
				return;
			}

			var cellData = Setting.cellDataMap[index];
			var newCellData = cellData;

			EditorGUILayout.LabelField ("坐标", Setting.IndexToCoord (index).ToString ());
			using (HorizontalScope.New ())
			{
				newCellData.tileIndex = EditorGUILayout.IntField ("地块", cellData.tileIndex);
				EditorGUILayout.LabelField (Setting.GetTileSetting (cellData.tileIndex)?.name ?? "Null");
			}
			using (HorizontalScope.New ())
			{
				newCellData.buildingOrientation = EditorGUILayoutEX.EnumPopup ("朝向", cellData.buildingOrientation.Direction);
				EditorGUILayout.LabelField (cellData.buildingOrientation.GetArrow ());
			}
			if (GUILayout.Button ("设为中心", GUILayout.MaxWidth (120)))
			{
				Setting.SetGridCenter (Setting.IndexToCoord (index));
			}

			Setting.cellDataMap[index] = newCellData;
		}

		TileSettingObject GetTileSetting (int id)
		{
			if (id >= 0 && id < Setting.tileSettings.Count)
			{
				return Setting.tileSettings[id];
			}
			return null;
		}

		void Btn_ClearTiles ()
		{
			var array = Setting.cellDataMap;
			for (int i = 0; i < array.Length; i++)
			{
				var celldata = array[i];
				celldata.tileIndex = -1;
				Setting.cellDataMap[i] = celldata;
			}
		}

		void Btn_ClearBuildings ()
		{
			var array = Setting.cellDataMap;
			for (int i = 0; i < array.Length; i++)
			{
				var celldata = array[i];
				celldata.buildingIndex = -1;
				celldata.buildingOrientation = default;
				Setting.cellDataMap[i] = celldata;
			}
		}

	}
}